var gulp = require('gulp-param')(require('gulp'), process.argv),
  minifycss = require('gulp-minify-css'),
  concat = require('gulp-concat'),
  clean = require('gulp-clean'),
  htmlmin = require('gulp-htmlmin'),
  uglify = require('gulp-uglify'),
  jsmin = require('gulp-jsmin'),
  rename = require('gulp-rename'),
  ngAnnotate = require('gulp-ng-annotate'),
  inject = require('gulp-inject'),
  injectString = require('gulp-inject-string'),
  angularFilesort = require('gulp-angular-filesort'),
  server = require('gulp-server-livereload'),
  templateCache = require('gulp-angular-templatecache'),
  sass = require("gulp-sass"),
  replace = require('gulp-replace'),
  sourcemaps = require('gulp-sourcemaps'),
  sort = require('gulp-sort'),
  plumber = require('gulp-plumber');
var $ = require('gulp-load-plugins')();

var sassPath = ['./scss/theme.scss', './scss/**/*.scss', '!./scss/ionic.app.scss', './www/component/**/*.scss', './www/pages/**/*.scss']
gulp.task('sass', function () {
  var sassOptions = {
    outputStyle: 'expanded',
    precision: 10
  };

  var injectFiles = gulp.src(sassPath, {
    read: false
  });

  var injectOptions = {
    starttag: '// injector',
    endtag: '// endinjector',
    addRootSlash: false
  };

  return gulp.src(
    ['./temp/bundle.scss']
  )
    .pipe(plumber())
    .pipe($.inject(injectFiles, injectOptions))
    .pipe(sourcemaps.init())
    .pipe($.sass(sassOptions))
    .pipe(sourcemaps.write())
    .pipe(sass().on('error', sass.logError))
    .pipe(plumber.stop())
    .pipe(gulp.dest("www/css"));
});

gulp.task('mock', function () {
  // return gulp.src('./www/pages/**/*.mock')
  //   .pipe(concat('allMock.js'))
  //   .pipe(gulp.dest('./www'))


  return gulp.src('./www/mock.js')
    .pipe(inject(gulp.src(['./www/pages/**/*.mock.json']), {
      starttag: '/* inject:mock */',
      endtag:'/* endinject:mock */',
      transform: function (filePath, file,i,length) {
        // return file contents as string
        if(file.contents){
          var content = file.contents.toString().trim();
          return content.substring(1,content.length-1)+(i + 1 < length ? ',' : '');
        }
        else{
          return '';
        }

      }
    }))
    .pipe(gulp.dest('./www'));
});


//自动引用Js 和Css
//自动生成Index.html
gulp.task('inject', ["sass", "mock", "template"], function () {

  var injectStyles = gulp.src([
    "./www/css/ionic.app.css",
    "./www/css/**/*.css"
  ], {
    read: false
  });

  var injectAngularScripts = gulp.src([
    './www/app.module.js',
    './www/app.run.js',
    './www/app.config.js',
    './www/app.route.js',
    './www/mock.js',
    './www/templates.js',
    './www/**/*.js',
    '!./www/lib/**/*.js'
  ], {
    read: false
  })

  var injectOptions = {
    ignorePath: ['www'],
    addRootSlash: false
  };

  return gulp.src('./www/index.html')
    .pipe(inject(injectStyles, injectOptions)) // Not necessary to read the files (will speed up things), we're only after their paths
    .pipe(inject(injectAngularScripts, injectOptions))
    .pipe(gulp.dest("./www"));
});

gulp.task('template', function () {
  return gulp.src(['./www/pages/**/*.html',"./www/component/directive/**/*.html"])
    .pipe(sort())
    .pipe(templateCache("templates.js",
      {
        transformUrl: function(url) {
          url = url.replace('directive/','');
          url = url.replace('component/','');
          return url;
        }
      }
    ))
    .pipe(gulp.dest('www'));
});


gulp.task('serve', ['inject'], function (test, prod) {
  gulp.src('./www/')
    .pipe(server({
      livereload: true,
      port: 8081,
      open: true,
      defaultFile: "index.html"
    }));

  gulp.watch(sassPath, ['sass']);
  gulp.watch('./www/pages/**/*.mock.json', ['mock']);
  gulp.watch(['./www/pages/**/*.html',"./www/component/directive/**/*.html"], ['template']);
  gulp.watch('./www/**.*.js',['inject'])

});

// gulp.task('clean', function() {
//     return gulp.src(['release','temp'], {
//             read: false
//         })
//         .pipe(clean());
// });
